﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Ecopsy.Tools
{
    /// <summary>
    /// Object Data Source. заточен под постраничную выборку из БД
    /// в качестве источника - делегат на функцию    экземпляр делегата обязан уметь тащить постранично из бд 
    /// Формат делегата -  GetPage(int startRowIndex, int maximumRows, out int RowCount);
    /// </summary>
    public class ObjectDS_PF : IEnumerator, IEnumerable
    {
        public delegate object[] GetPage(int startRowIndex, int endRowIndex, out int RowCount);        

        private int _сurrent = 0;
        private object[] _arr = null;
        private int _RowCount = 0;

        private GetPage _SourceFunction = null;
        private object _ParamOfFunction = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SourceFunction"></param>
        /// <param name="ParamOfFunction"></param>
        public ObjectDS_PF(GetPage SourceFunction)
        {
            _SourceFunction = SourceFunction;        
        }

        public ObjectDS_PF() { }

        private void InitSource(object sender, ObjectDataSourceEventArgs e)
        {
            e.ObjectInstance = this;
        }



        #region IEnumerator Members

        public object Current
        {
            get { return _arr[_сurrent]; }
        }

        public bool MoveNext()
        {
            if (_сurrent + 1 > _arr.Length) return false;
            _сurrent++;
            return true;


        }

        public void Reset()
        {
            _сurrent = 0;
        }

        #endregion

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            return this;
        }

        #endregion

        #region Select
        public object[] Select()
        {            
            return null;
        }

        public object[] Select(int startRowIndex, int maximumRows)
        {         
            _arr = _SourceFunction(startRowIndex+1 , startRowIndex+maximumRows, out _RowCount);
            return _arr;
        }

        public int GetCount()
        {
            return _RowCount;
        }

        #endregion



        public ObjectDataSource ImAsObjectDataSource
        {
            get
            {
                ObjectDataSource Result;
                Result = new ObjectDataSource(this.GetType().FullName, "Select");
                Result.SelectCountMethod = "GetCount";

         
                Result.EnablePaging = true;
                Result.ObjectCreating += new ObjectDataSourceObjectEventHandler(InitSource);
                return Result;
            }
        }


    }

    
}
